package com.lsh.controller;

import com.lsh.service.IndexService;
import com.lsh.container.CommentContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Map;

/**
 * 长轮询消息推送模块
 * @author Administrator
 * @date 2019/10/29 23:54
 */
@RestController
@RequestMapping("/poll")
public class PollingController {

    @Autowired
    IndexService indexService;

    @Autowired
    CommentContainer commentContainer;

    /**
     * 推送评价消息
     * @param token
     * @return
     */
    @GetMapping("/comment")
    public DeferredResult getCommentMessage(@CookieValue("TOKEN") String token){
        String userId = indexService.findByUserId(token);
        DeferredResult result = new DeferredResult(30000L, "time out");
        Map<String, DeferredResult> container = commentContainer.getCommentContainer();
        container.put(userId, result);
        System.out.println("当前的长轮询请求数为：" + container.size());
        result.onCompletion(new Runnable() {
            @Override
            public void run() {
                //无论请求是否超时，都会执行run方法中的业务
                container.remove(userId);
                System.out.println("当前的长轮询请求数为：" + container.size());
            }
        });
        return result;
    }

}
